//
//  IMSimpleLoginC.m
//  IMModel
//
//  Created by jimneylee on 14-5-19.
//  Copyright (c) 2014年 jimneylee. All rights reserved.
//

#import "IMSimpleLoginC.h"
#import "HYLoginInfo.h"
#import "HYXMPPManager.h"
#import "HYUtils.h"
#import "YHRequest.h"

@interface IMSimpleLoginC ()

@end

@implementation IMSimpleLoginC

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Init/dealloc methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)dealloc
{
    [self removeAllObserver];
}

- (id)init
{
    self = [super init];
    if (self) {
        [self registerNotification];
    }
    return self;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark View lifecycle
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"登录";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.logoImageView];
    [self.view addSubview:self.userIDField];
    [self.view addSubview:self.passwordField];
    [self.view addSubview:self.loginBtn];
//    [self.view addSubview:self.registerBtn];
    
    CGFloat y = 150.0 * [UIScreen mainScreen].bounds.size.width/375;
    [self layoutSubviewsWithY:y];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                 action:@selector(tapAction)];
    [self.view addGestureRecognizer:tapGesture];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    HYLoginInfo *loginInfo = [HYLoginInfo sharedInstance];
    self.userIDField.text = loginInfo.user.length ? loginInfo.user : @"";
}

-(void)layoutSubviewsWithY:(CGFloat )y
{
    self.logoImageView.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width-90)/2.0f, y, 90, 90);
    
    y = y + 90 +40;
    self.userIDField.frame = CGRectMake(40, y, [UIScreen mainScreen].bounds.size.width - 80, 45);
    y = y + 45 +35;
    self.passwordField.frame = CGRectMake(40, y, [UIScreen mainScreen].bounds.size.width - 80, 45);
    y = y + 45 +38;
    self.loginBtn.frame = CGRectMake(40, y, [UIScreen mainScreen].bounds.size.width - 80, 45);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Private
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)setField:(UITextField *)field forKey:(NSString *)key
{
    if (field.text != nil) {
        [[NSUserDefaults standardUserDefaults] setObject:field.text forKey:key];
    }
    else {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
    }
}

- (BOOL)checkInputValid
{
    BOOL valid = YES;
    
    if (self.userIDField.text.length == 0) {
        [HYUtils showWaitingMsg:self.userIDField.placeholder];
        [self.userIDField becomeFirstResponder];
        valid = NO;
    }
    else if (self.passwordField.text.length == 0) {
        [HYUtils showWaitingMsg:self.passwordField.placeholder];
        [self.passwordField becomeFirstResponder];
        valid = NO;
    }
    
    return valid;
}
    
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark lazy
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

-(UIImageView *)logoImageView
{
    if (!_logoImageView) {
        _logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width-90)/2.0f, 150, 90, 90)];
        _logoImageView.image = [UIImage imageNamed:@"icon_logo"];
    }
    return _logoImageView;
}

-(UITextField *)userIDField
{
    if(!_userIDField){
        _userIDField = [[UITextField alloc] initWithFrame:CGRectMake(40, 150+90+40, [UIScreen mainScreen].bounds.size.width - 80, 45)];
        _userIDField.placeholder=@"请输入账号";
        _userIDField.layer.cornerRadius = 22.5;
        _userIDField.backgroundColor = COLOR(229, 235, 246,1);
        
        UIView *lefv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 45)];
        lefv.backgroundColor = [UIColor clearColor];
        _userIDField.leftView = lefv;
        _userIDField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _userIDField;
}
-(UITextField *)passwordField
{
    if(!_passwordField){
        _passwordField = [[UITextField alloc] initWithFrame:CGRectMake(40, 150+90+40+45+35, [UIScreen mainScreen].bounds.size.width - 80, 45)];
        _passwordField.placeholder=@"请输入密码";
        _passwordField.layer.cornerRadius = 22.5;
        _passwordField.backgroundColor = COLOR(229, 235, 246,1);
        _passwordField.secureTextEntry = YES;
        
        UIView *lefv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 45)];
        lefv.backgroundColor = [UIColor clearColor];
        _passwordField.leftView = lefv;
        _passwordField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _passwordField;
}
-(UIButton *)loginBtn
{
    if(!_loginBtn){
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _loginBtn.backgroundColor = APP_MAIN_COLOR;
        _loginBtn.frame = CGRectMake(40, 150+90+40+45+35+45+38, [UIScreen mainScreen].bounds.size.width - 80, 45);
        _loginBtn.layer.cornerRadius = 22.5;
        [_loginBtn addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}
-(UIButton *)registerBtn
{
    if(!_registerBtn){
        _registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_registerBtn setTitle:@"注册" forState:UIControlStateNormal];
        [_registerBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        _registerBtn.backgroundColor = [UIColor lightGrayColor];
        _registerBtn.frame = CGRectMake(40, 150+90+40+45+35+45+38+45+35, [UIScreen mainScreen].bounds.size.width - 80, 45);
        _registerBtn.layer.cornerRadius = 22.5;
        [_registerBtn addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerBtn;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Actions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)loginAction:(id)sender
{
    if ([self checkInputValid]) {
        
        NSString *bareStr = [self.userIDField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSString * password = [self.passwordField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        [self loginKf:bareStr pwd:password];
    }
}

-(void)loginKf:(NSString *)bareStr pwd:(NSString *)password
{
    //test001dail12
    //sky888
//    if (![bareStr isEqualToString:@"test001dail12"]) {
//        [self loginOpenfire:bareStr pwd:password];
//        return;
//    }
    HYLoginInfo *loginInfo = [HYLoginInfo sharedInstance];
    // 删除两端空格
    NSRange atRange = [bareStr rangeOfString:@"@"];
    if (atRange.location == NSNotFound)
    {
        loginInfo.user = bareStr;
    } else {
        XMPPJID *jid = [XMPPJID jidWithString:bareStr];
        loginInfo.user = jid.user;
        //loginInfo.hostName = jid.domain;
    }
    loginInfo.skyPwd = password;
    
    NSString * url = [NSString stringWithFormat:@"%@&userName=%@&password=%@",kLoginUrl,bareStr,password];
    NSData * data = nil;
    YHRequest * request = [[YHRequest alloc] init];
    [HYUtils showWaitingMsg:@"校验中.."];
    [request postRequestWithUrl:url withData:data withSuccessed:^(NSDictionary * obj) {
        
        NSLog(@"成功：%@",obj);
        NSString * code = [NSString stringWithFormat:@"%@",[obj objectForKey:@"code"]];
        if ([@"0" isEqualToString:code]) {
            NSDictionary * result= [obj objectForKey:@"result"];
            if (result) {
                NSDictionary * superior = [result objectForKey:@"superior"];
                if (superior && [superior isKindOfClass:[NSDictionary class]]) {
                    loginInfo.superior = [superior objectForKey:@"userName"];
                    [loginInfo saveUserInfoToSanbox];
                }
            }
            
            [self loginOpenfire:bareStr pwd:@"123456"];
            [HYUtils clearWaitingMsg];
        }else{
            NSString * msg = [obj objectForKey:@"msg"];
            if (!msg.length) {
                msg = @"账号或密码错误!";
            }
            [HYUtils alertWithErrorMsg:msg];
        }
    } withFailed:^(NSError *error) {
        [HYUtils alertWithErrorMsg:@"登录失败，请求会员系统异常，请稍后再试"];
        NSLog(@"请求失败：%@",error);
    }];
}

-(void)loginOpenfire:(NSString *)bareStr pwd:(NSString *)password
{
    HYLoginInfo *loginInfo = [HYLoginInfo sharedInstance];
    // 删除两端空格
    NSRange atRange = [bareStr rangeOfString:@"@"];
    if (atRange.location == NSNotFound)
    {
        loginInfo.user = bareStr;
    } else {
        XMPPJID *jid = [XMPPJID jidWithString:bareStr];
        loginInfo.user = jid.user;
        //loginInfo.hostName = jid.domain;
    }
    loginInfo.password = password;
    
    __weak typeof(self) weakSelf = self;
    [[HYXMPPManager sharedInstance] xmppUserLogin:^(HYXMPPConnectStatus status) {
        [weakSelf handleResultType:status];
    }];
}

- (void)handleResultType:(HYXMPPConnectStatus)status{
    
    MAIN(^{ // 主线程刷新UI
        switch (status) {
            case HYXMPPConnectStatusConnecting:
            {
                [HYUtils showWaitingMsg:@"请稍候..."];
                break;
            }
            case HYXMPPConnectStatusDidConnect:
            {
                [HYUtils showWaitingMsg:@"请稍候..."];
                break;
            }
            case HYXMPPConnectStatusDisConnect:
            {
                [HYUtils alertWithErrorMsg:@"与服务器断开连接 !"];
                break;
            }
            case HYXMPPConnectStatusTimeOut:
            {
                [HYUtils alertWithErrorMsg:@"网络连接超时 !"];
                break;
            }
            case HYXMPPConnectStatusAuthSuccess:
            {
                [HYUtils clearWaitingMsg]; // 隐藏
                [self enterMainPage];
                break;
            }
            case HYXMPPConnectStatusAuthFailure:
            {
                [HYUtils alertWithTitle:@"用户名或者密码不正确 !"];
                break;
            }
            default:{
                [HYUtils clearWaitingMsg]; // 隐藏
                break;
            }
        }
    });
    
}

- (void)enterMainPage{
    // 更改用户的登录状态为YES
    [HYLoginInfo sharedInstance].logon = YES;
    // 把用户登录成功的数据，保存到沙盒
    [[HYLoginInfo sharedInstance] saveUserInfoToSanbox];
    // 登录成功来到主界面
    [HYUtils initRootViewController];
}

- (void)tapAction
{
    [self.userIDField resignFirstResponder];
    [self.passwordField resignFirstResponder];
}


#pragma mark 增加注册通知
- (void)registerNotification
{
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)removeAllObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
/**
 *  文字改变
 */
- (BOOL)textFieldTextDidChange:(NSNotification *)noti
{
    NSString *userStr = [self.userIDField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *pwdStr = [self.passwordField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (userStr.length && pwdStr.length) {
        self.loginBtn.enabled = YES;
        self.loginBtn.alpha = 1.0;
    } else {
        self.loginBtn.enabled = NO;
        self.loginBtn.alpha = 0.8;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.userIDField) { //next
        [self.passwordField becomeFirstResponder];
    } else { // done
        [self loginAction:nil];
    }
    return YES;
}

#pragma mark 键盘
- (void)handleKeyboardWillHide:(NSNotification *)notification
{
    NSDictionary *keyBoardDic = notification.userInfo;
    [UIView animateWithDuration:[keyBoardDic[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        
        [self layoutSubviewsWithY:150.0 * [UIScreen mainScreen].bounds.size.width/375];
    } completion:^(BOOL finished) {
    }];
}

- (void)handleKeyboardDidShow:(NSNotification *)notification
{
    NSDictionary *keyBoardDic = notification.userInfo;
    
    [UIView animateWithDuration:[keyBoardDic[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        
        [self layoutSubviewsWithY:50.f * [UIScreen mainScreen].bounds.size.width/375];
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
